package Executer;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import View.PopUp;

import Controller.Tasker;
import Events.GenericEvent;

public class ExecuterTask implements Runnable{
	private Tasker tasker;
	private Timer timer;
	final ScheduledExecutorService exec;
	private Vector<GenericEvent> queueTask;
	ExecuterTask et;
	public ExecuterTask(Tasker task)
	{
		this.tasker=task;
		//timer = new Timer();
		exec = Executors.newSingleThreadScheduledExecutor();
		//new Thread(this).start();
		et=this;
	}

	public void waitingForNextDay() //Es para programar que diariamente se ponga las tareas que se tienen que ejecutar.
	{
		Date t = new Date();
		Date d2 = new Date(t.getYear(), t.getMonth(), t.getDate()+1);
		exec.schedule(new TimerTask(){
			public void run() {
				tasker.prepareNewTask();
			}
		}, System.currentTimeMillis()-d2.getTime(), TimeUnit.MILLISECONDS);
	}
	public void executedPopUp(GenericEvent event)
	{
		new PopUp(event, tasker.getGenericFrame().getCV(), tasker);
	}
	public void run() {
//		while(true)
//		{
//			//tasker.getExecutedEvent()
//		}
	}
	public synchronized void newExecuted(GenericEvent evento)
	{
//		Date d = new Date(evento.getD_Start().getYear(),evento.getD_Start().getMonth(), evento.getD_Start().getDate()
//				,evento.getT_Start().getHours(),evento.getT_Start().getMinutes(),evento.getT_Start().getSeconds());
		Date d= new Date();
//		timer.schedule(new ExecutedTask(evento), evento.getD_Start());
		final GenericEvent ge = evento;
//		evento.
		//queueTask.add(evento);
		Runnable run= new Runnable() {
			public void run() {
				// TODO Auto-generated method stubhttp://www.youtube.com/watch?feature=player_embedded&v=oTMRpd4AuOc
				new ExecutedTask(ge, et);
			}
		};
//		System.out.println(new Date(System.currentTimeMillis()));
//		exec.schedule(run, d.getTime()-System.currentTimeMillis(), TimeUnit.MILLISECONDS);
		exec.schedule(run, d.getTime()+1000, TimeUnit.MILLISECONDS);
	}

	public void evenentExecuted(GenericEvent event) {
		for(int i=0; i<queueTask.size(); i++)
			if(event==queueTask.elementAt(i))
				queueTask.remove(i);
	}
}
